<?php
$loader->requireOnce('includes/Sanitize.class.php');
$loader->requireOnce('includes/CommonConstant.class.php');
$loader->requireOnce('includes/CoreErrorCode.class.php');
$loader->requireOnce('includes/EnumException.class.php');
$loader->requireOnce('includes/EnumerationConstant.class.php');
class Utils {
	//
	/**
	 * Trim date and month if they are '00'
	 *
	 * @param String $delimiter the delemiter / or - ..
	 * @param String $date
	 */
	public function trimDate($delimiter ,$date) {
		$arr = explode($delimiter, $date);
		if ($arr[0] == '00') {
			$date = substr($date, 3);
		}
		if ($arr[1] == '00') {
			$date = substr($date, 3);
		}
		return $date;
	}

	public static function trimNumber($number, $delimiter=".") {
        $arr  =   explode($delimiter, $number);
        $faction    =   preg_replace("/0+$/", '', $arr[1]);
        $res    =   $arr[0];
        if (!empty($faction)) {
            $res    =   $arr[0] . $delimiter . $faction;
        }

        return $res;
	}

	public static function trimNumberOfArray($array, $field) {
	   if(is_array($array)) {
	       foreach ($array as &$item) {
                if(array_key_exists($field,$item)) {
                    $item[$field]   =   self::trimNumber($item[$field]);
                }
	       }
	   }

	   return $array;
	}

	/**
	 * Date difference in days
	 *
	 * @param 'yyyy-mm-dd' $greaterDate
	 * @param 'yyyy-mm-dd' $pastDate
	 * @return days difference
	 */
	function dateDiff($greaterDate, $pastDate) {
		//calculate the difference in seconds.
		$difference = strtotime($greaterDate) - strtotime($pastDate);
		//calculate the number of days
		return round(((($difference/60)/60)/24), 0);
	}

	/**
	 * Sanitize text before import into database
	 *
	 * @param String $str
	 * @return sanitized string
	 */
	public static function sanitizeText($str, $deleteNL=true) {
		if (strlen($str) == 0) {
			return $str;
		}
		$str = Sanitize::html($str, true);
		$str = Sanitize::stripAll($str);
		if($deleteNL){
			$str = Sanitize::escape($str);
		}
		if (strlen($str) == 0) {
			$str = "";
		}
		return $str;
	}

	/**
	 * Enter description here...
	 *
	 * @param String $day short (Mon) or long (Monday) day
	 */
	public static function toVietnameseDay($day, $abbr = false) {
		$currentDay = strtolower($day);
		switch ($currentDay) {
			case 'mon':
				if ($abbr) return L10nHelper::_('T.2'); else return L10nHelper::_('Monday');
			case 'monday':
				if ($abbr) return L10nHelper::_('T.2');  else return L10nHelper::_('Monday');

			case 'tue':
				if ($abbr) return L10nHelper::_('T.3');  else return L10nHelper::_('Tuesday');
			case 'tuesday':
				if ($abbr) return L10nHelper::_('T.3');  else return L10nHelper::_('Tuesday');

			case 'wed':
				if ($abbr) return L10nHelper::_('T.4');  else return L10nHelper::_('Wednesday');
			case 'wednesday':
				if ($abbr) return L10nHelper::_('T.4');  else return L10nHelper::_('Wednesday');

			case 'thu':
				if ($abbr) return L10nHelper::_('T.5');  else return L10nHelper::_('Thursday');
			case 'thursday':
				if ($abbr) return L10nHelper::_('T.5');  else return L10nHelper::_('Thursday');

			case 'fri':
				if ($abbr) return L10nHelper::_('T.6');  else return L10nHelper::_('Friday');
			case 'friday':
				if ($abbr) return L10nHelper::_('T.6');  else return L10nHelper::_('Friday');

			case 'sat':
				if ($abbr) return L10nHelper::_('T.7');  else return L10nHelper::_('Saturday');
			case 'saturday':
				if ($abbr) return L10nHelper::_('T.7');  else return L10nHelper::_('Saturday');

			case 'sun':
				if ($abbr) return L10nHelper::_('CN');  else return L10nHelper::_('Sunday');
			case 'sunday':
				if ($abbr) return L10nHelper::_('CN');  else return L10nHelper::_('Sunday');

			default:
				if ($abbr) return ''; else return L10nHelper::_('Invalid day');
		}

	}

	public static function getVNeseCurrentDate() {
		$date = date('Y/m/d');
		return self::toVietnameseDay(date('D'), true) . ' ' . L10nHelper::renderDateTime($date);
	}

	public static function sanitizeAndCaseTitle($input) {
		$input = mb_convert_case($input, MB_CASE_TITLE, "UTF-8");
		return Utils::sanitizeText($input);
	}

	public static function getProtocol() {
		$proto = "https://";
		$config = Celini::configInstance();
		$forcehttps = $config->get('forceHTTPS');
		if (!isset($_SERVER['HTTPS']) && !$forcehttps) {
			$proto= "http://";
		}
		return $proto;
	}

	public static function getAppContext() {
		$config = Celini::configInstance();
		return $config->get('app_context');
	}

	public static function getAppUrl() {
		$port = '';
		if ($_SERVER['SERVER_PORT'] != 80) {
			$port = ':' . $_SERVER['SERVER_PORT'];
		}
		return self::getProtocol() . $_SERVER['SERVER_NAME'] . $port . "/" . self::getAppContext();
	}

	public static function get12PreviousMonths(){
		$curMonth = date('n');
		$curYear = date('Y');
		$monthList[0] = '--';
		for ($i = 1; $i <= 12; $i++){
			$monthList['1/'.$curMonth."/".$curYear.'-'.date('t',mktime(0,0,0,$curMonth,1,$curYear)).'/'.$curMonth."/".$curYear] = Utils::getMonth($curMonth)." ".L10nHelper::_("year %s",$curYear);
			$curMonth--;
			if ($curMonth == 0){
				$curMonth = 12;
				$curYear--;
			}
		}
		return $monthList;
	}

	public static function get4PreviousQuaters(){
		$curMonth = date('n');
		$curYear = date('Y');
		$curQuarter = ceil($curMonth/3);
		$quarterList[0] = '--';
		// To get month of quater: currentMonth*3
		for ($i = 0; $i < 4; $i++){
			$quarterList['1/'.($curQuarter*3-2)."/".$curYear.'-'.date('t',mktime(0,0,0,$curQuarter*3,1,$curYear)).'/'.($curQuarter*3)."/".$curYear] = L10nHelper::_("Quarter")." ".$curQuarter." ".L10nHelper::_("quarteryear %s",$curYear);
			$curQuarter--;
			if ($curQuarter == 0){
				$curQuarter = 4;
				$curYear--;
			}
		}
		return $quarterList;
	}
	public static function sanitizeWard($ward){
		if(is_numeric($ward)){
			return "P. ".$ward;
		}
		return self::sanitizeAndCaseTitle($ward);
	}

	public static function ceilCurrency($number, $ceilUnit=1000){
		$res	=	ceil($number/$ceilUnit);
		return $res*$ceilUnit;
	}

	public static function allowShowRecentPatientHeader($userName) {
		$user = Celini::newORDO('User');

		$isDoctor = $user->checkRole($userName, User::ROLE_DOCTOR_ID);
		$isBilling = $user->checkRole($userName, User::ROLE_BILLING_ID);

		return ($isDoctor || $isBilling);

	}
	public static function getDateMap($key) {
		$day = array(
			1 => L10nHelper::_('Sunday'),
			2 => L10nHelper::_('Monday'),
			3 => L10nHelper::_('Tuesday'),
			4 => L10nHelper::_('Wednesday'),
			5 => L10nHelper::_('Thurday'),
			6 => L10nHelper::_('Friday'),
			7 => L10nHelper::_('Saturday')
		);
		return $day[$key];
	}
	/**
	 * return Month of passed value from 1 to 12
	 * Jan. Feb. Mar. Apr. May June July Aug. Sept. Oct. Nov. Dec.
	 */
	public static function getMonth($month) {
		switch ( $month ) {
			case 1:	return L10nHelper::_("Jan");
			break;
			case 2:	return L10nHelper::_("Feb");
			break;
			case 3:	return L10nHelper::_("Mar");
			break;
			case 4:	return L10nHelper::_("Apr");
			break;
			case 5:	return L10nHelper::_("May");
			break;
			case 6:	return L10nHelper::_("Jun");
			break;
			case 7:	return L10nHelper::_("Jul");
			break;
			case 8:	return L10nHelper::_("Aug");
			break;
			case 9:	return L10nHelper::_("Sep");
			break;
			case 10:	return L10nHelper::_("Oct");
			break;
			case 11:	return L10nHelper::_("Nov");
			break;
			case 12:	return L10nHelper::_("Dec");
			break;

			default:
				break;
		}

	}
	/**
	 * $emrClassName: emr class name
	 * $emrMethodName: part of emr method name
	 * $paras: list of parameters
	 *
	 */
	public static function invokeEmr($emrClassName,$emrMethodName,$paras) {
		$loader = new ControllerFileLoader();
		if (!$loader->loadController($emrClassName)) {
			throw new EmrClassNotFoundException("Could not load emr class :[".$emrClassName."]");
		}
		$obj_name = "C_" . $emrClassName;
		$ctr =& new $obj_name();
		$action = 'action'.$emrMethodName;
		if (method_exists($ctr,$action) == false)
		{
			throw new EmrMethodNotFoundException("Could invoke emr class method :[".$action."]");
		}
		return $ctr->$action($paras);
	}

	/**
	 * Get the 'enumeration_id' value of a specific group name
	 * @param $enumGroupName
	 * @return enumeration_id
	 */
	public static function getEnumGroupName($enumGroupName){
        $enumObj	=	ORDataObject::factory('EnumerationDefinition');
        $enum		=	$enumObj->fromName($enumGroupName);
        return $enum->get('enumeration_id');
	}

    /**
     * Get the key of given enum
     * @param $enumGroup
     * @param $enumValue
     * @return key of given enum
     */
    public static function getEnumKey($enumGroup, $enumValue) {
       $em = EnumManager::getInstance();
        $enumKey = $em->lookupKey($enumGroup,$enumValue);
        if ($enumKey == false) {
            throw new EnumException("Not support enum [ $enumGroup,$enumValue ]",
            CoreErrorCode::LOAD_ENUM_FAIL);
        }
        return $enumKey;
    }

    /**
     * Get the value of given enum
     * @param $enumGroup
     * @param $enumKey
     * @return value of given enum
     */
    public static function getEnumValue($enumGroup, $enumKey) {
    	$em = EnumManager::getInstance();
        return $em->lookup($enumGroup, $enumKey);
    }

    public static function getEnumTextByKey($enumGroup, $enumKey) {
       $em = EnumManager::getInstance();
        return $em->lookupLocalizedTextByKey($enumGroup,$enumKey);
    }

    public static function getEnumTextByValue($enumGroup, $enumValue) {
       $em = EnumManager::getInstance();
        return $em->lookupLocalizedTextByValue($enumGroup,$enumValue);
    }
    /**
     * get enum array
     * @param $enumGroup
     * @return array([column value in tb enumeration_value]=>[localized text])
     */
    public static function getEnumArrayValue($enumGroup) {
    	$em = EnumManager::getInstance();
    	return $em->enumArrayValueLocalized($enumGroup);
    }

    /**
     * get enum array
     * @param $enumGroup
     * @return array([column key in tb enumeration_value]=>[localized text])
     */
    public static function getEnumArrayKey($enumGroup) {
        $em = EnumManager::getInstance();
        return $em->enumArrayKeyLocalized($enumGroup);
    }

    /**
     * Get the day range from a given start date and a end date.
     *
     * @param string $startDate ISO-formatted start date
     * @param string $endDate ISO-formatted start date
     * @return a list of continuos localizied dates
     */
    public static function getDateList($startDate, $endDate){
        // Check valid dates
        if ((($start = strtotime($startDate))===false) || (($end = strtotime($endDate))===false)) {
        	   throw new Exception("Invalid input date strings");
        }
        $dateList   =   array();
        $iterDate   =   $endDate;
        while($start <= $end){
            // Insert date to result array
        	$val    =   L10nHelper::renderDateTime($iterDate);
            $dateList[$val]  =   $val;
            // To previous date
            $parts      =   explode("-", $iterDate);
            $iterDate   =   date ("Y-m-d", mktime(0, 0, 0, $parts[1], $parts[2]-1, $parts[0]));
            $end        =   strtotime($iterDate);
        }

        return $dateList;
    }

    public static function getNumberParaFromGet($name, $default=CommonConstant::DB_NULL_POSITIVE_NUMBER) {
    	if (isset($_GET[$name]) && $_GET[$name] != CommonConstant::JS_NULL_NUMBER) {
    		return $_GET[$name];
    	}
    	return $default;
    }

    public static function getPatientPicFolder($patienCode) {
        global $config;

        return $config['patient_pic_folder'] . $patienCode . '.jpg';

    }

    /**
     * Get a array from an input array and a given config array.
     * Example: inputData=array(
     *     0 => array('personId' => "101", "personName" => "Nguyen Van A", "age" => 30)
     *     1 => array('personId' => "102", "personName" => "Tran B", "age" => 32))
     *   configArray = array(
     *      'id'    => "personId",
     *      'name'  =>  array("personName", "age")
     *      'delimeter' =>  " "
     *   )
     *
     *   return: array(
     *      "101"   => "Nguyen Van A 30",
     *      "102"   =>  "Tran B 32"
     *   )
     * @author PPDong, 2009-12-28
     * @param array $inputData Input data array
     * @param array $configArray Info of fieled of input array to be used to create return array.
     */
    public static function getArrayKeyValue($inputData, $configArray) {
        if (!is_array($inputData)) {
            return array();
        }
        $res    =   array();
        $keyField   =   $configArray['id'];
        $delimeter  =   $configArray['delimeter'];
        foreach ($inputData as $item) {
            $name       =   '';
            if (is_array($configArray['name'])) {
                foreach ($configArray['name'] as $nameCol) {
                    $name   .=  $item[$nameCol]. $delimeter;
                }
            }
            else {
                $name  .=  $item[$configArray['name']]. $delimeter;
            }
            $name   =   substr($name, 0, strlen($name)-strlen($delimeter));
            $res[$item[$keyField]]  =   $name;
        }
        return $res;
    }

    public static function buildOptionsList($arrData, $fieldValue, $fieldTitle) {
        if (!is_array($arrData)) {
            return '';
        }
        $html = '';
        foreach ($arrData as $item) {
            $value    =   $item[$fieldValue];
            $title    =   $item[$fieldTitle];
        	$html  .=  "<option title='$title' value='$value'>$title</option>";
        }

        return $html;

    }
}
?>